package datensaetze;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import exceptions.IllFormattedLineException;
import utils.GNDStringUtils;

public class LineOfSubfields {

	private final ArrayList<Subfield> subfields;

	public List<Subfield> getSubfields() {
		return Collections.unmodifiableList(subfields);
	}

	public LineOfSubfields(
			String contentOfLine,
			char implicitIndicator,
			boolean idnInExclamationMarks) throws IllFormattedLineException {
		String[] subfieldStrings =
			GNDStringUtils.splitInSubfields(contentOfLine,
					implicitIndicator, idnInExclamationMarks);
		subfields = new ArrayList<Subfield>(8);
		for (int i = 0; i < subfieldStrings.length; i++) {
			Subfield sub = new Subfield(subfieldStrings[i]);
			subfields.add(sub);
		}
	}

	public Subfield getFirstSubfieldWith(char indikator) {
		for (Subfield subfield : subfields) {
			if (subfield.getIndicator() == indikator)
				return subfield;
		}
		return null;
	}

	public int getFirstIndexOf(char indikator) {
		for (int i = 0; i < subfields.size(); i++) {
			if (subfields.get(i).getIndicator() == indikator)
				return i;
		}
		return -1;
	}

	public int getFirstIndexOf(char indikator, int start) {
		for (int i = start; i < subfields.size(); i++) {
			if (subfields.get(i).getIndicator() == indikator)
				return i;
		}
		return -1;
	}

	public Subfield getFirstSubfieldWith(char indikator, int start) {
		for (int i = start; i < subfields.size(); i++) {
			if (subfields.get(i).getIndicator() == indikator)
				return subfields.get(i);
		}
		return null;
	}

	public String getAN() {
		String s = "";
		for (Subfield subfield : subfields) {
			s += "$" + subfield.getIndicator() + subfield.getContent();
		}
		return s;
	}

	/**
	 * @param args
	 * @throws IllFormattedLineException 
	 */
	public static void main(String[] args) throws IllFormattedLineException {
		LineOfSubfields feld =
			new LineOfSubfields("$ax$by$az", 'a', false);
		System.out.println(feld.getFirstSubfieldWith('a').getContent());
		System.out.println(feld.getFirstSubfieldWith('b').getContent());
		System.out.println(feld.getFirstSubfieldWith('a', 2).getContent());
		System.out.println(feld.getFirstSubfieldWith('a', 3));
		System.out.println(feld.getFirstIndexOf('a', 3));
		System.out.println(feld.getFirstIndexOf('a'));
		System.out.println(feld.getFirstIndexOf('b'));
		feld =
			new LineOfSubfields("Genau!$vRUmsetzung GND aus RAK-M 2003",
					'a', false);
		System.out.println(feld.getAN());
	}

}
